using B.S.Data.MES.API.Applications.BaseData.Command.SupplierCommand;
using B.S.Domain.BasicData.SupplierManagement;
using B.S.Infratrctrue;
using B.S.Requst;
using MediatR;
using System.Linq;
using System.Threading.Tasks;

namespace B.S.Data.MES.API.Applications.BaseData.CommandHandlers.SupplierCommandHandlers
{
    public class ListSupplierCommandHandlers : IRequestHandler<ListSupplierCommand, APIRequst<APIPageing<List<Supplier>>>>
    {
        private readonly IBaseRepository<Supplier> supplierRepository;

        public ListSupplierCommandHandlers(IBaseRepository<Supplier> supplierRepository)
        {
            this.supplierRepository = supplierRepository;
        }

        public  Task<APIRequst<APIPageing<List<Supplier>>>> Handle(ListSupplierCommand request, CancellationToken cancellationToken)
        {
            var query = supplierRepository.GetAll();
            var totalCount = query.Count();
            var total = (int)System.Math.Ceiling(1.0 * totalCount / request.PageSize);
            var suppliers = query.OrderBy(x => x.SupplierId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);
            APIPageing<List<Supplier>> Page = new APIPageing<List<Supplier>>();
            Page.Data = suppliers.ToList();
            Page.Total= total;
            Page.TotalCount= totalCount;
            return Task.FromResult(new APIRequst<APIPageing<List<Supplier>>>
            {
                 Data = Page,
                 Code=RequstCode.成功,
                 Msg = "获取供应商列表成功"
                 
            });
        }
    }
}